package com.bupt.kgplatform.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bupt.kgplatform.common.FTPUtil;
import com.bupt.kgplatform.common.RetResult;
import com.bupt.kgplatform.entity.Material;
import com.bupt.kgplatform.entity.apibo.MaterialPageResult;
import com.bupt.kgplatform.service.MaterialService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhuyunfei
 * @since 2022-11-04
 */
@RestController
@RequestMapping("/kgplatform/material")
public class MaterialController {

    @Autowired
    MaterialService materialService;


    //上传单个素材
    @PostMapping("/upload")
    public RetResult upload(MultipartFile upfiles,
                            String title,
                            String author,
                            String source,
                            String publish_time) throws IOException {
        try {
                //获取文件原始名称
                String oldFileName = upfiles.getOriginalFilename();
                //获取文件后缀
                String extension = "." + FilenameUtils.getExtension(upfiles.getOriginalFilename());
                //生成新的文件名称
                String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
                //文件类型
                String type = upfiles.getContentType();
                //处理根据日期生成目录
                //String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
                String dateDirPath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

                //文件上传
                byte[] bytes = upfiles.getBytes();
                FTPUtil.sftpLogin();
                FTPUtil.Sftpupload(bytes, newFileName, dateDirPath);
                FTPUtil.sftpLogout();
                //本地路径
                //            //文件路径拼装
                //            String uploadpath = "D:";
                //            String dateDirPath = uploadpath + "/files/" + dateDirPath;
                //            //处理文件上传
                //            File dateDir = new File(dateDirPath);
                //            if (!dateDir.exists()) dateDir.mkdirs();
                //            upfiles.transferTo(new File(dateDir, newFileName));

                //将文件信息放入数据库保存
                Material userFile = new Material();
                userFile.setOldFileName(oldFileName);
                userFile.setNewFileName(newFileName);
                userFile.setExt(extension);
                userFile.setType(type);
                userFile.setPath(dateDirPath);
                userFile.setTitle(title);
                userFile.setAuthor(author);
                userFile.setSource(source);
                userFile.setPublishTime(publish_time);
                userFile.setUploadTime(LocalDateTime.now());
                materialService.save(userFile);
        }
        catch (Exception e){
            return new RetResult(400, e.getMessage());
        }
        return new RetResult(200,"上传成功");
    }


    @PostMapping("download")
    public void download(@RequestParam(required = true)Integer id, HttpServletResponse response) throws IOException {
        OutputStream os = null;
        InputStream is = null;
        try {
            Material userFile = materialService.getById(id);
            String newfilename = userFile.getNewFileName();
            String fileType = userFile.getType();//文件类型
            String relativePath =userFile.getPath();
            //读取流
            FTPUtil.sftpLogin();
            is = FTPUtil.Sftpdownload(newfilename,relativePath);

            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            //跨域解决
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            //response头放文件类型
            response.addHeader("Access-Control-Expose-Headers", "fileType");

            //Content-Disposition中指定的类型是文件的扩展名，并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的，点保存后，文件以filename的值命名，
            // 保存类型以Content中设置的为准。注意：在设置Content-Disposition头字段之前，一定要设置Content-Type头字段。
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String(newfilename));
            //Header返回文件类型
            response.addHeader("fileType", fileType);
            //复制
            IOUtils.copy(is, response.getOutputStream());

            FTPUtil.sftpLogout();
            response.getOutputStream().flush();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //文件的关闭放在finally中
        finally
        {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //删除单个素材
    @PostMapping("/delete")
    public RetResult delete(@RequestParam(required = true)Integer id) throws FileNotFoundException {

        try{
            //根据id查询信息
            Material userFile = materialService.getById(id);
            if(userFile!=null) {
                //删除文件
                FTPUtil.sftpLogin();
                String relativePath =userFile.getPath();
                FTPUtil.Sftpdelete(userFile.getNewFileName(),relativePath);//立即删除
                FTPUtil.sftpLogin();
            }
            else {
                return new RetResult(400, "文件不存在");
            }
            //删除数据库中记录
            materialService.removeById(id);
        }
        catch (Exception e){
            return new RetResult(400, e.getMessage());
        }
        return new RetResult(200,"删除成功");
    }

    //根据领域查找现有素材
//    @PostMapping("/findbyfield")
//    public RetResult getbyfield(@RequestParam(required = true)String field) {
//        try {
//            List<Material> userFiles = materialService.findByField(field);
//            return new RetResult(200, "查询成功!", userFiles);
//        }
//        catch (Exception e){
//            return new RetResult(400, e.getMessage());
//        }
//    }

    //获得所有素材信息
    @PostMapping("/findall")
    public RetResult getall() {
        try {
            List<Material> userFiles = materialService.list();
            return new RetResult(200, "查询成功!", userFiles);
        }
        catch (Exception e){
            return new RetResult(400, e.getMessage());
        }
    }

    //按页条件查询获得素材信息
    @PostMapping("/findbypage")
    public RetResult getbypage(@RequestParam(required = true)Integer page,
                               @RequestParam(required = true)Integer limit,
                               @RequestParam(required = false) String title) {
        try {
            //分页参数
            Page<Material> pageseting = Page.of(page,limit);

            QueryWrapper<Material> wrapper = new QueryWrapper();
            wrapper.like("title",title);
            Page<Material> materialFiles = materialService.page(pageseting,wrapper);//获得数据
            MaterialPageResult data = new MaterialPageResult();
            data.count = materialFiles.getTotal();//获得数据条数
            data.queryResult=materialFiles.getRecords();
            return new RetResult(200, "查询成功!", data);
        }
        catch (Exception e){
            return new RetResult(400, e.getMessage());
        }
    }


}
